package com.health.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.wf.captcha.utils.CaptchaUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.health.entity.UserModel;
import com.health.service.UserService;
import com.health.entity.UserModel;
import com.health.service.MenuService;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Random;
import java.util.HashMap;
import java.util.Map;

@Controller
public class CommunalController {

    @Resource
    private UserService userService;
    @Resource
    private MenuService menuService;


    /**
     * 用户的登录
     * @param user
     * @param session
     * @param verCode
     * @return
     */
    @PostMapping("/api/login")
    @ResponseBody
    public R login(UserModel user, String captcha, HttpSession session, HttpServletRequest request){
        // 判断验证码是否正确
        if (!CaptchaUtil.ver(captcha, request)) {
            return R.failed("验证码不正确");
        }
        // 根据用户名查询用户
        QueryWrapper<UserModel> queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_name", user.getUserName());
        UserModel loginUser = userService.getOne(queryWrapper);
        // 如果查询用户为空, 则该用户不存在
        if(loginUser == null){
            return R.failed("该用户不存在!");
        // 如果查询用户不为空, 则将查询出来的密码和传入的密码对比
        }else if(!loginUser.getPassword().equals(user.getPassword())){
            return R.failed("用户名或密码错误!");
        }else{
            // 登录成功, 将用户对象存入session中
            session.setAttribute("loginUser", loginUser);
            return R.ok(loginUser);
        }
    }

    /**
     * 用户注册
     * @param session
     * @param request
     * @return
     */
    @PostMapping("/api/register")
    @ResponseBody
    public R register(UserModel userModel, String code, HttpSession session, HttpServletRequest request){

        UserModel loginUser = (UserModel) session.getAttribute("loginUser");
        // session中获取验证码
        String sessionCode = (String) session.getAttribute("code");
        if(loginUser == null){
            if(code == null || !code.equals(sessionCode)){
                return R.failed("验证码不正确!");
            }
        }
        String userName = userModel.getUserName();
        String password = userModel.getPassword();
        UserModel user = userService.getOne(new QueryWrapper<UserModel>().eq("user_name", userName));
        // 判断该用户名是否已存在
        if(user != null){
            return R.failed("该用户名已存在!");
        }else{
            UserModel inserUser = new UserModel();
            inserUser.setUserName(userName);
            inserUser.setPassword(password);
            userService.save(inserUser);
        }
        return R.ok(null);
    }

    /**
     * 退出登录功能
     * @param request
     * @return
     */
    @GetMapping("/api/logout")
    public String logout(HttpServletRequest request){
        request.getSession().removeAttribute("loginUser");
        return "/login/login";
    }

    /**
     * 生成验证码图片
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        CaptchaUtil.out(130, 35, 4, request, response);
    }

    /**
         * 查询菜单列表, 返回前端, 以便前端渲染菜单
         * @param session
         * @return
         */
        @GetMapping("/api/selectMenuList")
        @ResponseBody
        public Map<String, Object> selectMenuList(HttpSession session){
            // 从session获取登录用户
            UserModel loginUser = (UserModel)session.getAttribute("loginUser");
            HashMap<String, Object> param = new HashMap<>();
            // 设置查询菜单列表的参数: 顶部菜单值, 和用户角色
            param.put("role", loginUser.getRole());
            return menuService.selectMenuList(param);
        }

        /**
         * 查询首页
         * @param topMenuName
         * @param session
         * @return
         */
        @GetMapping("/api/selectMainMenu")
        @ResponseBody
        public R selectMainMenu(String topMenuName, HttpSession session){
            // 如果顶端菜单名称为空, 则设置默认值: contentManagement
            topMenuName = topMenuName == null ? "contentManagement":topMenuName;
            // 从session获取登录用户
            UserModel loginUser = (UserModel)session.getAttribute("loginUser");
            HashMap<String, Object> param = new HashMap<>();
            // 设置查询菜单列表的参数: 顶部菜单值, 和用户角色
            param.put("topMenuName", topMenuName);
            param.put("role", loginUser.getRole());
            return menuService.selectMainMenu(param);
        }

        /**
         * 页面跳转控制器
         * @param pageName
         * @return
        */
        @RequestMapping("/pages/{pageName}")
        public String getPageInfo(@PathVariable String pageName){
            return pageName;
        }

}
